package io.github.wppli.trigger.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import io.github.wppli.domain.user.event.AdjustUserFollowedEvent;
import io.github.wppli.domain.user.service.AdjustAccountService;
import io.github.wppli.types.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author li--jiaqiang 2025−03−03
 */
@Slf4j
@Component
public class AdjustUserFollowedCustomer {

    @Value("${spring.rabbitmq.topic.adjust_user_followed}")
    private String topic;

    private final AdjustAccountService accountService;

    public AdjustUserFollowedCustomer(AdjustAccountService accountService) {
        this.accountService = accountService;
    }

    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.adjust_user_followed}"))
    public void listener(String message) {
        try {
            // 转换对象
            BaseEvent.EventMessage<AdjustUserFollowedEvent.AdjustUserFollowedMessage> eventMessage =
                    JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<AdjustUserFollowedEvent.AdjustUserFollowedMessage>>() {
                    }.getType());

            AdjustUserFollowedEvent.AdjustUserFollowedMessage data = eventMessage.getData();
            Long targetUserId = data.getTargetUserId();
            Long userId = data.getUserId();
            Boolean followed = data.getFollowed();
            try {
                log.info("监听用户取关-关注调整成功消息，进行取关-关注 topic: {} message: {}", topic, message);
                // 调整数据库的关注数量
                accountService.adjustFollowCount(userId, targetUserId, Boolean.TRUE.equals(followed));
            } catch (Exception e) {
                log.error("监听用户取关-关注消息，消费失败 topic: {} message: {}", topic, message);
                accountService.adjustFolloweeCountRedis(userId, targetUserId, Boolean.FALSE.equals(followed));
                accountService.adjustFollowerCountRedis(userId, targetUserId, Boolean.FALSE.equals(followed));
                e.printStackTrace();
                // throw e;
            }
        } catch (Exception e) {
            log.error("外 - 监听用户取关-关注消息，消费失败 topic: {} message: {}", topic, message);
            e.printStackTrace();
        }
    }
}